package com.itanqing.demo.study03;




import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;

public class NIOClient {

    public static void main(String[] args) throws Exception {

        // 创建一个SocketChannel
        SocketChannel socketChannel = SocketChannel.open();

        // 设置非阻塞
        socketChannel.configureBlocking(false);

        InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 6666);

        // 如果没有连接成功
        if (!socketChannel.connect(inetSocketAddress)) {
            while (!socketChannel.finishConnect()) {
                System.out.println("因为连接需要时间, 客户端不会阻塞, 可以做其他工作......");
            }
        }

        // 如果连接成功 就发数据
        String message = "Hello Flower";

        // Wraps a byte array into a buffer. (包装一个字节数组到Buffer)
        ByteBuffer buffer = ByteBuffer.wrap(message.getBytes(StandardCharsets.UTF_8));

        int write = socketChannel.write(buffer);

        System.out.println("写入字节数: " + write);

        // 阻塞
        int read = System.in.read();
    }
}
